'use strict';

const Controller = require('egg').Controller;
const fs = require('fs')
const path = require('path')
class UploadController extends Controller {
  // 上传单个图片
  // async image() {
  //   const { ctx } = this;

  //   try {
  //     const file = ctx.request.files[0];
  //     if (!file) {
  //       ctx.throw(400, '请选择文件');
  //     }

  //     // 暂时返回模拟的上传结果
  //     const imageUrl = `/uploads/demo/${Date.now()}_${file.filename}`;

  //     ctx.body = {
  //       code: 200,
  //       message: '上传成功',
  //       data: {
  //         url: imageUrl,
  //         filename: file.filename,
  //         size: file.size,
  //       },
  //     };
  //   } catch (error) {
  //     ctx.throw(500, error.message);
  //   }
  // }
  // 在后端 UploadController 中修改
async image() {
  const { ctx, app } = this;

  try {
    const file = ctx.request.files[0];
    if (!file) {
      ctx.throw(400, '请选择文件');
    }

    // 生成唯一文件名
    const ext = path.extname(file.filename);
    const filename = `${Date.now()}_${Math.random().toString(36).substr(2)}${ext}`;
    
    // 保存文件到服务器指定目录
    const targetPath = path.join(app.config.static.dir, 'uploads', filename);
    const reader = fs.createReadStream(file.filepath);
    const writer = fs.createWriteStream(targetPath);
    
    await new Promise((resolve, reject) => {
      reader.pipe(writer);
      writer.on('finish', resolve);
      writer.on('error', reject);
    });

    // 返回真实的访问URL
    const imageUrl = `/public/uploads/${filename}`;

    ctx.body = {
      code: 200,
      message: '上传成功',
      data: {
        url: imageUrl,
        filename: filename,
        size: file.size,
      },
    };
  } catch (error) {
    ctx.throw(500, error.message);
  }
}

  // 批量上传图片
  async multiple() {
    const { ctx } = this;

    try {
      const files = ctx.request.files;
      if (!files || files.length === 0) {
        ctx.throw(400, '请选择文件');
      }

      const results = [];
      for (const file of files) {
        const imageUrl = `/uploads/demo/${Date.now()}_${file.filename}`;
        results.push({
          url: imageUrl,
          filename: file.filename,
          size: file.size,
        });
      }

      ctx.body = {
        code: 200,
        message: '上传成功',
        data: results,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 删除文件
  async delete() {
    const { ctx } = this;
    const filePath = ctx.params.path;

    try {
      // 暂时返回成功，实际应该删除文件
      ctx.body = {
        code: 200,
        message: '删除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = UploadController;
